import { FC, useEffect, useRef, useMemo, useState, useCallback } from 'react';
import dayjs from 'dayjs';
import classNames from 'classnames';
import ReactECharts from 'echarts-for-react';
import { fetchPredictedValueByTime } from '../../context/services/anomaly';
import styles from './index.module.less';
import { TrendData } from '../BGContainer/useCharts';

// 自定义ECharts系列类型，用于解决TS类型问题
interface CustomChartSeries {
  name: string;
  data: any[]; // 可以是number[]或[string, number][]
  type: 'line';
  smooth?: boolean;
  showSymbol?: boolean;
  tagDesc?: string;
  itemStyle?: {
    color?: string;
    borderColor?: string;
    borderWidth?: number;
  };
  lineStyle?: {
    color?: string;
    width?: number;
    type?: 'solid' | 'dashed' | 'dotted';
  };
  markPoint?: {
    data: {
      name: string;
      coord: any[];
      itemStyle?: {
        color?: string;
        borderColor?: string;
        borderWidth?: number;
      };
    }[];
  };
  markLine?: {
    silent?: boolean;
    symbol?: string | string[];
    lineStyle?: {
      color?: string;
      type?: 'solid' | 'dashed' | 'dotted';
      width?: number;
    };
    label?: {
      show?: boolean;
      position?: string;
      formatter?: any;
      color?: string;
      fontSize?: number;
      backgroundColor?: string;
      padding?: number[];
    };
    data?: any[];
  };
  markArea?: {
    silent?: boolean;
    itemStyle?: {
      color?: string;
      opacity?: number;
    };
    data?: any[][];
  };
}

interface ChartPointModalProps {
  visible: boolean;
  title?: string;
  type?: "red" | "yellow" | "green" | "gray"; // 添加类型属性，与MarkerInfo一致
  pointData?: {
    name: string; // 时间点
    value: any; // 值
    dataIndex: number;
    seriesIndex: number;
  };
  position?: {
    x: number;
    y: number;
  };
  evaluationItemName?: string; // 添加评估项名称
  tagName?: string; // 添加标签名称
  markerChartData?: any; // 添加从MarkerInfo传递过来的图表数据
  predictTime?: string; // 添加预测时间点
  upperLimit?: number; // 上限值
  lowerLimit?: number; // 下限值
  onClose: () => void;
}


const ChartPointModal: FC<ChartPointModalProps> = ({
  visible,
  title = '数据点详情',
  type = 'green', // 默认使用green类型
  pointData,
  position,
  evaluationItemName,
  tagName,
  markerChartData, // 添加从MarkerInfo传递过来的图表数据
  predictTime, // 添加预测时间点
  upperLimit, // 上限值
  lowerLimit, // 下限值
  onClose
}) => {
  const modalRef = useRef<HTMLDivElement>(null);
  const [loading, setLoading] = useState<boolean>(false);
  const [chartData, setChartData] = useState<any>(null);
  // 添加历史预测值数据状态
  const [historyPredictData, setHistoryPredictData] = useState<{ times: string[], values: string[] }>({
    times: [],
    values: []
  });
  // 添加一个ref来记录模态框是否已经打开过
  const hasOpenedRef = useRef<boolean>(false);

  // 使用useCallback缓存handleClose函数
  const handleClose = useCallback(() => {
    // 清除图表数据
    setChartData(null);
    // 调用外部传入的关闭函数
    onClose();
  }, [onClose]);

  // 监听visible变化，当弹窗关闭时清除图表数据
  useEffect(() => {
    if (!visible) {
      setChartData(null);
      setLoading(false);
    }
  }, [visible]);

  // 处理点击外部关闭
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (modalRef.current && !modalRef.current.contains(event.target as Node)) {
        handleClose();
      }
    };

    if (visible) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [visible, handleClose]);

  // 获取预测值数据
  // evaluationItemName and tagName are likely stable during modal visibility
  const fetchData = useCallback(async (targetTimeOverride?: string) => {
    console.log("fetchData", evaluationItemName, tagName, pointData, predictTime)
    if (!evaluationItemName || !tagName) {
      console.warn("Missing evaluationItemName or tagName for fetchData");
      return;
    }
    try {
      setLoading(true);
      // 注意：这里不再直接设置 markerChartData
      // Determine target time
      let targetTime = dayjs();
      if (targetTimeOverride) {
        targetTime = dayjs(targetTimeOverride);
        console.log("Fetching history based on target time:", targetTimeOverride);
      } else if (pointData && pointData.name) { // Use pointData only if no override
        targetTime = dayjs(pointData.name);
      } else if (predictTime) { // Use predictTime if no override and no pointData
        targetTime = dayjs(predictTime);
      }
      const startTime = targetTime.format('YYYY-MM-DD HH:mm:ss');
      const endTime = predictTime;

      const params = {
        startTime,
        endTime,
        evaluationItemName,
        tagName
      };

      console.log('请求历史预测值数据，参数:', params);
      const res = await fetchPredictedValueByTime(params);

      if (res.status) {
        console.log('历史预测值数据获取成功:', res.content);
        if (res.content && res.content.tagTimeAndValueMapping) {
          const timeValueMapping = res.content.tagTimeAndValueMapping;
          const times: string[] = [];
          const values: string[] = [];
          Object.entries(timeValueMapping).forEach(([time, value]) => {
            times.push(time);
            values.push(value as string);
          });
          const sortedIndices = times.map((_, index) => index)
            .sort((a, b) => new Date(times[a]).getTime() - new Date(times[b]).getTime());
          const sortedTimes = sortedIndices.map(i => times[i]);
          const sortedValues = sortedIndices.map(i => values[i]);
          setHistoryPredictData({ times: sortedTimes, values: sortedValues });
        } else {
          setHistoryPredictData({ times: [], values: [] }); // Clear if no data
        }
      } else {
        console.error('获取历史预测值数据失败:', res.message);
        setHistoryPredictData({ times: [], values: [] }); // Clear on error
      }
    } catch (err: any) {
      console.error('获取历史预测值数据出错:', err);
      setHistoryPredictData({ times: [], values: [] }); // Clear on error
    } finally {
      setLoading(false); // Stop loading indicator for history fetch
    }
  }, [evaluationItemName, tagName, pointData, predictTime]); // Dependencies needed for targetTime calculation *if not overridden*

  // 修改useEffect，只有在首次打开或visible从false变为true时设置chartData
  useEffect(() => {
    if (visible) {
      if (!hasOpenedRef.current) {
        // 只有在首次打开时设置chartData
        if (markerChartData && !pointData) {
          console.log("Setting initial chart data from markerChartData");
          setChartData(markerChartData);
        } else {
          setChartData(markerChartData);
          console.log("Fetching initial history data");
          fetchData();
        }
        hasOpenedRef.current = true;
      }
    } else {
      // 当模态框关闭时，重置状态
      setChartData(null);
      setHistoryPredictData({ times: [], values: [] });
      hasOpenedRef.current = false;
    }
  }, [visible]);  // 只依赖于visible，不再依赖markerChartData

  // 获取弹窗容器的类名，基于类型添加对应的样式
  const getModalClassName = () => {
    return classNames(
      styles['modal-container'],
      {
        [styles['visible']]: visible,
        [styles['modal-red']]: type === 'red',
        [styles['modal-yellow']]: type === 'yellow',
        [styles['modal-green']]: type === 'green',
      }
    );
  };

  // 创建一个通用的tooltip格式化函数，处理所有场景下的日期显示和数据展示
  const createTooltipFormatter = (rawTimes?: string[], allDisplayTimes?: string[]) => {
    // 获取当前函数作用域的颜色映射
    const colorMap = {
      'red': 'rgba(255, 77, 79, 1)',
      'yellow': 'rgba(250, 173, 20, 1)',
      'green': 'rgba(82, 196, 26, 1)',
      'gray': 'rgba(191, 191, 191, 1)',
      'default': 'rgba(3, 251, 255, 1)'
    };

    const currentMainColor = colorMap[type as keyof typeof colorMap] || colorMap.default;
    
    const currentColorArray = [
      currentMainColor,
      'rgba(255, 145, 0, 1)',
      'rgba(0, 208, 132, 1)',
      'rgba(51, 133, 255, 1)',
      'rgba(245, 34, 45, 1)'
    ];
    
    return function(params: any) {
      console.log("params", params)
      const axisValue = params[0].axisValue || '';
      let formattedTime = axisValue;
      try {
        // 如果有原始时间数组，尝试从中获取完整时间
        if (params[0].value instanceof Array) {
          formattedTime = params[0].value?.[0];
        }
      } catch (err) {
        console.error('日期格式化错误:', err);
        formattedTime = dayjs(axisValue).format('YYYY-MM-DD HH:mm:ss');
      }
      // 3. 构建tooltip内容
      let result = `<div style="font-weight:bold;margin-bottom:5px;">${formattedTime}</div>`;
      // 添加所有系列的数据
      params.forEach((param: any) => {
        // 根据系列名称确定颜色
        let color;
        if (param.seriesName === '实际值') {
          color = currentMainColor;
        } else if (param.seriesName === '当前预测值') {
          color = currentMainColor;
        } else if (param.seriesName === '历史预测值') {
          color = 'rgba(150, 150, 220, 1)'; // 历史预测值使用特定颜色
        } else {
          // 对于其他系列（通常是多线图中的其他数据线），直接从currentColorArray获取
          color = currentColorArray[param.seriesIndex % currentColorArray.length];
        }
        
        // 获取值（处理数组格式）
        const value = param.value instanceof Array ? param.value[1] : param.value;
        
        // 添加到结果中
        result += `<div style="display:flex;justify-content:space-between;align-items:center;margin:3px 0">
          <span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:${color}"></span>
          <span style="flex:1">${param.seriesName}:</span>
          <span style="font-weight:bold;float:right">${value}</span>
        </div>`;
      });
      
      // 添加上限值和下限值（如果存在）
      if (upperLimit !== undefined) {
        result += `<div style="display:flex;justify-content:space-between;align-items:center;margin:3px 0">
          <span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:rgba(255,255,255,0.5)"></span>
          <span style="flex:1">上限值:</span>
          <span style="font-weight:bold;float:right">${upperLimit}</span>
        </div>`;
      }
      
      if (lowerLimit !== undefined) {
        result += `<div style="display:flex;justify-content:space-between;align-items:center;margin:3px 0">
          <span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:rgba(255,255,255,0.5)"></span>
          <span style="flex:1">下限值:</span>
          <span style="font-weight:bold;float:right">${lowerLimit}</span>
        </div>`;
      }
      
      return result;
    };
  };
  // 获取ECharts的配置，与MarkerInfo保持一致
  const getChartOptions = useMemo(() => {
    // 基础颜色映射
    const colorMap = {
      'red': 'rgba(255, 77, 79, 1)',
      'yellow': 'rgba(250, 173, 20, 1)',
      'green': 'rgba(82, 196, 26, 1)',
      'gray': 'rgba(191, 191, 191, 1)',
      'default': 'rgba(3, 251, 255, 1)'
    };

    // 获取主要颜色
    const mainColor = colorMap[type as keyof typeof colorMap] || colorMap.default;

    // 辅助颜色数组（用于多线图）
    const colorArray = [
      mainColor,
      'rgba(255, 145, 0, 1)',
      'rgba(0, 208, 132, 1)',
      'rgba(51, 133, 255, 1)',
      'rgba(245, 34, 45, 1)'
    ];
    
    // 创建上下限的标记线和区域配置 - 仅用于单线图
    const getLimitMarkOptions = () => {
      // 检查是否同时有上限和下限
      if (upperLimit !== undefined && lowerLimit !== undefined) {
        return {
          markLine: {
            silent: true,
            symbol: 'none',
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.5)',
              type: 'dashed',
              width: 1
            },
            label: {
              show: true,
              position: 'end',
              formatter: (params: any) => {
                return params.name;
              },
              color: 'rgba(255, 255, 255, 0.8)',
              fontSize: 12,
              backgroundColor: 'rgba(0, 0, 0, 0.3)',
              padding: [2, 4]
            },
            data: [
              { yAxis: upperLimit, name: '上限' },
              { yAxis: lowerLimit, name: '下限' }
            ]
          },
          markArea: {
            silent: true,
            itemStyle: {
              color: 'rgba(255, 255, 255, 0.1)'
            },
            data: [
              [
                { yAxis: lowerLimit },
                { yAxis: upperLimit }
              ]
            ]
          }
        };
      }
      
      return {};
    };

    // 检查是否有历史预测值数据可以展示
    const hasHistoryPredictData = historyPredictData &&
      historyPredictData.times &&
      historyPredictData.times.length > 0 &&
      historyPredictData.values &&
      historyPredictData.values.length > 0;

    // 如果有图表数据
    if (chartData) {
      // 判断是否为多线图
      const isMultiLine = Array.isArray(chartData) && chartData.length > 1;

      if (isMultiLine) {
        // 多线图情况 - 类似MarkerInfo中的param模式
        const allTrendData = chartData as TrendData[];

        // 找出所有时间点并排序，使用Map确保唯一性
        // 使用Map来合并时间点，以标准化的时间格式作为键
        const timeMap = new Map<string, string>();

        // 处理所有趋势数据的时间点
        allTrendData.forEach(trend => {
          if (trend && trend.times) {
            trend.times.forEach(time => {
              // 使用标准化的时间格式作为键
              const standardTime = dayjs(time).format('YYYY-MM-DD HH:mm:ss');
              // 保存原始时间字符串
              timeMap.set(standardTime, time);
            });
          }
        });

        // 如果有历史预测值数据，也加入到同一个Map中
        if (hasHistoryPredictData) {
          historyPredictData.times.forEach(time => {
            const standardTime = dayjs(time).format('YYYY-MM-DD HH:mm:ss');
            timeMap.set(standardTime, time);
          });
        }

        // 转换回数组并排序
        const allTimes = Array.from(timeMap.values()).sort((a, b) =>
          new Date(a).getTime() - new Date(b).getTime()
        );

        // 格式化为X轴标签
        const xAxisData = allTimes.map(time => {
          try {
            return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
          } catch (err) {
            return time;
          }
        });
        console.log("allTrendData modal", allTrendData);
        // 构建多条系列数据
        const series = allTrendData.map((trend, index) => {
          if (!trend || !trend.values || !trend.times) return null;

          // 将数据转换为[时间, 值]格式以确保数据点正确对应
          const dataPoints = trend.times.map((time, timeIdx) => {
            // 查找时间在allTimes中的索引
            const idx = allTimes.findIndex(t =>
              dayjs(t).format('YYYY-MM-DD HH:mm:ss') === dayjs(time).format('YYYY-MM-DD HH:mm:ss')
            );

            if (idx >= 0 && timeIdx < trend.values.length) {
              return [xAxisData[idx], trend.values[timeIdx]];
            }
            return null;
          }).filter(point => point !== null);

          return {
            name: trend.tagDesc || `数据${index + 1}`,
            data: dataPoints,
            type: 'line',
            smooth: true,
            tagDesc: trend.tagDesc,
            itemStyle: {
              color: '#fff',
              borderColor: colorArray[index % colorArray.length],
              borderWidth: 1,
            },
            lineStyle: {
              color: colorArray[index % colorArray.length],
              width: 2,
            },
            ...getLimitMarkOptions()
          } as CustomChartSeries;
        }).filter(Boolean) as CustomChartSeries[];

        // 如果有历史预测值数据，添加一个系列
        if (hasHistoryPredictData) {
          // 创建时间到索引的映射，以便精确匹配
          const timeToIndexMap = new Map();
          allTimes.forEach((time, index) => {
            // 格式化为统一格式进行比较
            const formattedTime = dayjs(time).format('YYYY-MM-DD HH:mm:ss');
            timeToIndexMap.set(formattedTime, index);
          });

          // 将历史预测值直接映射到对应的X轴位置
          const historyData: [string, number][] = [];

          historyPredictData.times.forEach((time, idx) => {
            const formattedTime = dayjs(time).format('YYYY-MM-DD HH:mm:ss');
            const xAxisIndex = timeToIndexMap.get(formattedTime);

            if (xAxisIndex !== undefined) {
              // 使用X轴标签作为x坐标，确保对齐
              historyData.push([xAxisData[xAxisIndex], parseFloat(historyPredictData.values[idx])]);
            }
          });

          // 添加历史预测值系列
          series.push({
            name: '历史预测值',
            data: historyData,
            type: 'line',
            smooth: true,
            showSymbol: false,
            itemStyle: {
              color: '#fff',
              borderColor: 'rgba(150, 150, 220, 1)',
              borderWidth: 1,
            },
            lineStyle: {
              color: 'rgba(150, 150, 220, 1)',
              width: 2,
              type: 'dashed'
            },
            ...getLimitMarkOptions()
          } as CustomChartSeries);
        }
        console.log("series", series)
        return {
          grid: {
            left: 50,
            right: 50,
            top: 30,
            bottom: 50,
          },
          dataZoom: [
            {
              type: 'inside',
              start: 0,
              end: 100,
              xAxisIndex: 0,
              filterMode: 'filter',
              zoomOnMouseWheel: true,
              moveOnMouseMove: true
            }
          ],
          legend: {
            data: series.map(item => item?.tagDesc || '').filter(name => name !== ''),
            top: 5,
            left: 'center',
            orient: 'horizontal',
            textStyle: {
              color: 'rgba(255, 255, 255, 0.8)',
              fontSize: 12,
            },
            itemWidth: 10,
            itemHeight: 10,
            itemGap: 10,
            icon: 'rect',
          },
          tooltip: {
            trigger: 'axis',
            formatter: createTooltipFormatter(allTimes, xAxisData),
            backgroundColor: 'rgba(50,50,50,0.9)',
            borderColor: 'rgba(255,255,255,0.3)',
            textStyle: {
              color: '#fff',
              fontSize: 12
            },
            padding: [8, 10]
          },
          xAxis: {
            type: 'time',
            axisLine: {
              show: true,
              lineStyle: { color: 'rgba(255, 255, 255, 0.3)' }
            },
            axisTick: { show: false },
            axisLabel: {
              color: 'rgba(255, 255, 255, 0.7)',
              fontSize: 10,
              rotate: 45,
              formatter: (value: string) => {
                return dayjs(value).format('HH:mm:ss');
              }
            },
          },
          yAxis: {
            type: 'value',
            show: true,
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: {
              show: true,
              lineStyle: { color: 'rgba(255, 255, 255, 0.1)' }
            },
            axisLabel: {
              show: true,
              color: 'rgba(255, 255, 255, 0.7)',
              fontSize: 10,
              formatter: (value: number) => value.toFixed(2)
            },
            min: (value: any) => {
              const calcMin = Math.floor(value.min) * 0.9;
              return lowerLimit !== undefined ? Math.min(calcMin, lowerLimit)  : calcMin;
            },
            max: (value: any) => {
              const calcMax = Math.ceil(value.max) * 1.1;
              return upperLimit !== undefined ? Math.max(calcMax, upperLimit) : calcMax;
            },
          },
          series: series,
        };
      } else {
        // 单线图情况
        const singleTrendData = Array.isArray(chartData) && chartData.length > 0
          ? chartData[0]
          : chartData;

        if (!singleTrendData || !singleTrendData.times || !singleTrendData.values) {
          // 如果没有有效数据，返回空配置
          return {};
        }

        // 收集所有时间点（包括实际数据和历史预测数据）
        // 使用Map来合并时间点，以标准化的时间格式作为键
        const timeMap = new Map<string, string>();

        // 处理原始数据的时间点
        singleTrendData.times.forEach(time => {
          // 使用标准化的时间格式作为键
          const standardTime = dayjs(time).format('YYYY-MM-DD HH:mm:ss');
          // 保存原始时间字符串
          timeMap.set(standardTime, time);
        });

        // 如果有历史预测值数据，也加入到同一个Map中
        if (hasHistoryPredictData) {
          historyPredictData.times.forEach(time => {
            const standardTime = dayjs(time).format('YYYY-MM-DD HH:mm:ss');
            timeMap.set(standardTime, time);
          });
        }

        // 转换回数组并排序
        const allTimes = Array.from(timeMap.values()).sort((a, b) =>
          new Date(a).getTime() - new Date(b).getTime()
        );

        // 格式化日期时间，只显示时:分
        const xAxisData = allTimes.map((time: string) => {
          try {
            return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
          } catch (err) {
            return time;
          }
        });
        console.log("predictTime", predictTime)
        // 处理有predictTime的情况
        if (predictTime) {
          // 将时间和值数据分割为实际值和预测值
          const splitIndex = singleTrendData.times.findIndex((time: string) =>
            dayjs(time).isAfter(dayjs(predictTime)) || dayjs(time).isSame(dayjs(predictTime))
          );

          // 如果找不到分割点或者所有数据都是实际值，则使用默认的单线图
          if (splitIndex === -1 || splitIndex >= singleTrendData.times.length) {
            // 构造系列数组
            // 将数据转换为[x, y]格式以确保与x轴对齐
            const dataPoints: [string, number][] = [];
            singleTrendData.times.forEach((time, idx) => {
              const timeIndex = allTimes.findIndex(t =>
                dayjs(t).format('YYYY-MM-DD HH:mm:ss') === dayjs(time).format('YYYY-MM-DD HH:mm:ss')
              );
              if (timeIndex >= 0 && idx < singleTrendData.values.length) {
                dataPoints.push([xAxisData[timeIndex], parseFloat(singleTrendData.values[idx])]);
              }
            });

            const series = [{
              name: '实际值',
              data: dataPoints,
              type: 'line',
              smooth: true,
              showSymbol: false,
              // 高亮当前点
              markPoint: pointData ? {
                data: [
                  {
                    name: '当前点',
                    coord: [pointData.dataIndex, parseFloat(pointData.value)],
                    itemStyle: {
                      color: '#fff',
                      borderColor: mainColor,
                      borderWidth: 2
                    }
                  }
                ]
              } : undefined,
              itemStyle: {
                color: '#fff',
                borderColor: mainColor,
                borderWidth: 1
              },
              lineStyle: {
                color: mainColor,
                width: 2,
              },
              ...(upperLimit !== undefined && lowerLimit !== undefined ? {
                markLine: {
                  silent: true,
                  symbol: 'none',
                  lineStyle: {
                    color: 'rgba(255, 255, 255, 0.5)',
                    type: 'dashed',
                    width: 1
                  },
                  label: {
                    show: true,
                    position: 'end',
                    formatter: (params: any) => {
                      return params.name;
                    },
                    color: 'rgba(255, 255, 255, 0.8)',
                    fontSize: 12,
                    backgroundColor: 'rgba(0, 0, 0, 0.3)',
                    padding: [2, 4]
                  },
                  data: [
                    { yAxis: upperLimit, name: '上限' },
                    { yAxis: lowerLimit, name: '下限' }
                  ]
                },
                markArea: {
                  silent: true,
                  itemStyle: {
                    color: 'rgba(255, 255, 255, 0.1)'
                  },
                  data: [
                    [
                      { yAxis: lowerLimit },
                      { yAxis: upperLimit }
                    ]
                  ]
                }
              } : {})
            } as CustomChartSeries];

            // 如果有历史预测值数据，添加一个系列
            if (hasHistoryPredictData) {
              // 创建时间到索引的映射，以便精确匹配
              const timeToIndexMap = new Map();
              allTimes.forEach((time, index) => {
                // 格式化为统一格式进行比较
                const formattedTime = dayjs(time).format('YYYY-MM-DD HH:mm:ss');
                timeToIndexMap.set(formattedTime, index);
              });

              // 将历史预测值直接映射到对应的X轴位置
              const historyData: [string, number][] = [];

              historyPredictData.times.forEach((time, idx) => {
                const formattedTime = dayjs(time).format('YYYY-MM-DD HH:mm:ss');
                const xAxisIndex = timeToIndexMap.get(formattedTime);

                if (xAxisIndex !== undefined) {
                  // 使用X轴标签作为x坐标，确保对齐
                  historyData.push([xAxisData[xAxisIndex], parseFloat(historyPredictData.values[idx])]);
                }
              });

              // 添加历史预测值系列
              series.push({
                name: '历史预测值',
                data: historyData,
                type: 'line',
                smooth: true,
                showSymbol: false,
                itemStyle: {
                  color: '#fff',
                  borderColor: 'rgba(150, 150, 220, 1)',
                  borderWidth: 1,
                },
                lineStyle: {
                  color: 'rgba(150, 150, 220, 1)',
                  width: 2,
                  type: 'dashed'
                },
                ...getLimitMarkOptions()
              } as CustomChartSeries);
            }

            return {
              grid: {
                left: 50,
                right: 50,
                top: 30,
                bottom: 50,
              },
              dataZoom: [
                {
                  type: 'inside',
                  start: 0,
                  end: 100,
                  xAxisIndex: 0,
                  filterMode: 'filter',
                  zoomOnMouseWheel: true,
                  moveOnMouseMove: true
                }
              ],
              legend: {
                data: series.map(item => item.name).filter(name => {
                  // 如果是"实际值"，检查对应系列的数据是否为空
                  if (name === '实际值') {
                    const actualSeries = series.find(s => s.name === '实际值');
                    return actualSeries && actualSeries.data && actualSeries.data.length > 0;
                  }
                  return true;
                }),
                top: 5,
                left: 'center',
                textStyle: {
                  color: 'rgba(255, 255, 255, 0.8)',
                  fontSize: 12,
                }
              },
              tooltip: {
                trigger: 'axis',
                formatter: createTooltipFormatter(singleTrendData.times, xAxisData),
                backgroundColor: 'rgba(50,50,50,0.9)',
                borderColor: 'rgba(255,255,255,0.3)',
                textStyle: {
                  color: '#fff',
                  fontSize: 12
                },
                padding: [8, 10]
              },
              xAxis: {
                type: 'time',
                axisLine: {
                  show: true,
                  lineStyle: { color: 'rgba(255, 255, 255, 0.3)' }
                },
                axisTick: { show: false },
                axisLabel: {
                  color: 'rgba(255, 255, 255, 0.7)',
                  fontSize: 10,
                  rotate: 45,
                  formatter: (value: string) => {
                    return dayjs(value).format('HH:mm:ss');
                  }
                },
              },
              yAxis: {
                type: 'value',
                show: true,
                axisLine: { show: false },
                axisTick: { show: false },
                splitLine: {
                  show: true,
                  lineStyle: { color: 'rgba(255, 255, 255, 0.1)' }
                },
                axisLabel: {
                  show: true,
                  color: 'rgba(255, 255, 255, 0.7)',
                  fontSize: 10,
                  formatter: (value: number) => value.toFixed(2)
                },
                min: (value: any) => {
                  const calcMin = Math.floor(value.min) * 0.9;
                  return lowerLimit !== undefined ? Math.min(calcMin, lowerLimit) : calcMin;
                },
                max: (value: any) => {
                  const calcMax = Math.ceil(value.max) * 1.1;
                  return upperLimit !== undefined ? Math.max(calcMax, upperLimit) : calcMax;
                },
              },
              series: series,
            };
          }

          // 分割数据
          const actualTimes = singleTrendData.times.slice(0, splitIndex);
          const actualValues = singleTrendData.values.slice(0, splitIndex);
          const predictTimes = singleTrendData.times.slice(splitIndex);
          const predictValues = singleTrendData.values.slice(splitIndex);

          // 创建时间和索引的映射
          const timeToIndexMap = new Map();
          allTimes.forEach((time, index) => {
            const formattedTime = dayjs(time).format('YYYY-MM-DD HH:mm:ss');
            timeToIndexMap.set(formattedTime, index);
          });

          // 映射实际值数据点
          const actualDataPoints: [string, number][] = [];
          actualTimes.forEach((time, idx) => {
            const formattedTime = dayjs(time).format('YYYY-MM-DD HH:mm:ss');
            const xIndex = timeToIndexMap.get(formattedTime);
            if (xIndex !== undefined && idx < actualValues.length) {
              actualDataPoints.push([xAxisData[xIndex], parseFloat(actualValues[idx])]);
            }
          });

          // 映射预测值数据点
          const predictDataPoints: [string, number][] = [];
          
          // 如果有实际值，将最后一个实际值点添加到预测值的开头，以确保曲线连续
          if (actualTimes.length > 0 && actualValues.length > 0) {
            const lastActualTime = actualTimes[actualTimes.length - 1];
            const lastActualValue = parseFloat(actualValues[actualValues.length - 1]);
            
            // 将最后一个实际点添加到预测线的起始位置
            const formattedTime = dayjs(lastActualTime).format('YYYY-MM-DD HH:mm:ss');
            const xIndex = timeToIndexMap.get(formattedTime);
            if (xIndex !== undefined) {
              predictDataPoints.push([xAxisData[xIndex], lastActualValue]);
            }
          }

          // 添加预测值数据点
          predictTimes.forEach((time, idx) => {
            const formattedTime = dayjs(time).format('YYYY-MM-DD HH:mm:ss');
            const xIndex = timeToIndexMap.get(formattedTime);
            if (xIndex !== undefined && idx < predictValues.length) {
              predictDataPoints.push([xAxisData[xIndex], parseFloat(predictValues[idx])]);
            }
          });

          // 构造系列数组
          const series: any[] = [
            {
              name: '实际值',
              data: actualDataPoints,
              type: 'line',
              smooth: true,
              showSymbol: false,
              itemStyle: {
                color: '#fff',
                borderColor: mainColor,
                borderWidth: 1,
              },
              lineStyle: {
                color: mainColor,
                width: 2,
              },
              ...getLimitMarkOptions()
            } as CustomChartSeries,
            {
              name: '当前预测值',
              data: predictDataPoints,
              type: 'line',
              smooth: true,
              showSymbol: false,
              itemStyle: {
                color: '#fff',
                borderColor: mainColor,
                borderWidth: 1,
              },
              lineStyle: {
                color: mainColor,
                width: 2,
                type: 'dashed' // 使用虚线表示预测值
              },
              ...getLimitMarkOptions()
            } as CustomChartSeries
          ];

          // 如果有历史预测值数据，添加一个系列
          if (hasHistoryPredictData) {
            // 创建时间到索引的映射，以便精确匹配
            const timeToIndexMap = new Map();
            allTimes.forEach((time, index) => {
              // 格式化为统一格式进行比较
              const formattedTime = dayjs(time).format('YYYY-MM-DD HH:mm:ss');
              timeToIndexMap.set(formattedTime, index);
            });

            // 将历史预测值直接映射到对应的X轴位置
            const historyData: [string, number][] = [];

            historyPredictData.times.forEach((time, idx) => {
              const formattedTime = dayjs(time).format('YYYY-MM-DD HH:mm:ss');
              const xAxisIndex = timeToIndexMap.get(formattedTime);

              if (xAxisIndex !== undefined) {
                // 使用X轴标签作为x坐标，确保对齐
                historyData.push([xAxisData[xAxisIndex], parseFloat(historyPredictData.values[idx])]);
              }
            });

            // 添加历史预测值系列
            series.push({
              name: '历史预测值',
              data: historyData,
              type: 'line',
              smooth: true,
              showSymbol: false,
              itemStyle: {
                color: '#fff',
                borderColor: 'rgba(32, 142, 231, 1)',
                borderWidth: 1,
              },
              lineStyle: {
                color: 'rgba(32, 142, 231, 1)',
                width: 2,
                type: 'dashed'
              },
              ...getLimitMarkOptions()
            } as CustomChartSeries);
          }
          console.log("series", series)
          // 创建实际值和预测值的系列配置
          return {
            grid: {
              left: 50,
              right: 50,
              top: 30,
              bottom: 50,
            },
            dataZoom: [
              {
                type: 'inside',
                start: 0,
                end: 100,
                xAxisIndex: 0,
                filterMode: 'filter',
                zoomOnMouseWheel: true,
                moveOnMouseMove: true
              }
            ],
            legend: {
              data: series.map(item => item.name).filter(name => {
                // 如果是"实际值"，检查对应系列的数据是否为空
                if (name === '实际值') {
                  const actualSeries = series.find(s => s.name === '实际值');
                  return actualSeries && actualSeries.data && actualSeries.data.length > 0;
                }
                return true;
              }),
              top: 5,
              left: 'center',
              textStyle: {
                color: 'rgba(255, 255, 255, 0.8)',
                fontSize: 12,
              }
            },
            tooltip: {
              trigger: 'axis',
              formatter: createTooltipFormatter([...actualTimes, ...predictTimes], xAxisData),
              backgroundColor: 'rgba(50,50,50,0.9)',
              borderColor: 'rgba(255,255,255,0.3)',
              textStyle: {
                color: '#fff',
                fontSize: 12
              },
              padding: [8, 10]
            },
            xAxis: {
              type: 'time',
              axisLine: {
                show: true,
                lineStyle: { color: 'rgba(255, 255, 255, 0.3)' }
              },
              axisTick: { show: false },
              axisLabel: {
                color: 'rgba(255, 255, 255, 0.7)',
                fontSize: 10,
                rotate: 45,
                formatter: (value: string) => {
                  return dayjs(value).format('HH:mm:ss');
                }
              },
              axisPointer: {
                value: dayjs(predictTime).format('HH:mm'),
                snap: true,
                lineStyle: {
                  color: 'rgba(255, 255, 255, 0.5)',
                  width: 1,
                  type: 'dashed'
                },
                label: {
                  show: true,
                  formatter: function () {
                    return '预测时间点';
                  },
                  backgroundColor: 'rgba(50, 50, 50, 0.7)'
                },
                handle: {
                  show: false
                }
              }
            },
            yAxis: {
              type: 'value',
              show: true,
              axisLine: { show: false },
              axisTick: { show: false },
              splitLine: {
                show: true,
                lineStyle: { color: 'rgba(255, 255, 255, 0.1)' }
              },
              axisLabel: {
                show: true,
                color: 'rgba(255, 255, 255, 0.7)',
                fontSize: 10,
                formatter: (value: number) => value.toFixed(2)
              },
              min: (value: any) => {
                const calcMin = Math.floor(value.min) * 0.9;
                return lowerLimit !== undefined ? Math.min(calcMin, lowerLimit) : calcMin;
              },
              max: (value: any) => {
                const calcMax = Math.ceil(value.max) * 1.1;
                return upperLimit !== undefined ? Math.max(calcMax, upperLimit) : calcMax;
              },
            },
            series: series
          };
        }
        // 构造系列数组
        // 将数据转换为[x, y]格式以确保数据点与x轴精确对齐
        const dataPoints: [string, number][] = [];
        singleTrendData.times.forEach((time, idx) => {
          const timeIndex = allTimes.findIndex(t =>
            dayjs(t).format('YYYY-MM-DD HH:mm:ss') === dayjs(time).format('YYYY-MM-DD HH:mm:ss')
          );
          if (timeIndex >= 0 && idx < singleTrendData.values.length) {
            dataPoints.push([xAxisData[timeIndex], parseFloat(singleTrendData.values[idx])]);
          }
        });

        const series = [{
          name: '实际值',
          data: dataPoints,
          type: 'line',
          smooth: true,
          showSymbol: false,
          // 高亮当前点
          markPoint: pointData ? {
            data: [
              {
                name: '当前点',
                coord: [pointData.dataIndex, parseFloat(pointData.value)],
                itemStyle: {
                  color: '#fff',
                  borderColor: mainColor,
                  borderWidth: 2
                }
              }
            ]
          } : undefined,
          itemStyle: {
            color: '#fff',
            borderColor: mainColor,
            borderWidth: 1
          },
          lineStyle: {
            color: mainColor,
            width: 2,
          },
          ...(upperLimit !== undefined && lowerLimit !== undefined ? {
            markLine: {
              silent: true,
              symbol: 'none',
              lineStyle: {
                color: 'rgba(255, 255, 255, 0.5)',
                type: 'dashed',
                width: 1
              },
              label: {
                show: true,
                position: 'end',
                formatter: (params: any) => {
                  return params.name;
                },
                color: 'rgba(255, 255, 255, 0.8)',
                fontSize: 12,
                backgroundColor: 'rgba(0, 0, 0, 0.3)',
                padding: [2, 4]
              },
              data: [
                { yAxis: upperLimit, name: '上限' },
                { yAxis: lowerLimit, name: '下限' }
              ]
            },
            markArea: {
              silent: true,
              itemStyle: {
                color: 'rgba(255, 255, 255, 0.1)'
              },
              data: [
                [
                  { yAxis: lowerLimit },
                  { yAxis: upperLimit }
                ]
              ]
            }
          } : {})
        } as CustomChartSeries];

        // 如果有历史预测值数据，添加一个系列
        if (hasHistoryPredictData) {
          // 创建时间到索引的映射，以便精确匹配
          const timeToIndexMap = new Map();
          allTimes.forEach((time, index) => {
            // 格式化为统一格式进行比较
            const formattedTime = dayjs(time).format('YYYY-MM-DD HH:mm:ss');
            timeToIndexMap.set(formattedTime, index);
          });

          // 将历史预测值直接映射到对应的X轴位置
          const historyData: [string, number][] = [];

          historyPredictData.times.forEach((time, idx) => {
            const formattedTime = dayjs(time).format('YYYY-MM-DD HH:mm:ss');
            const xAxisIndex = timeToIndexMap.get(formattedTime);

            if (xAxisIndex !== undefined) {
              // 使用X轴标签作为x坐标，确保对齐
              historyData.push([xAxisData[xAxisIndex], parseFloat(historyPredictData.values[idx])]);
            }
          });

          // 添加历史预测值系列
          series.push({
            name: '历史预测值',
            data: historyData,
            type: 'line',
            smooth: true,
            showSymbol: false,
            itemStyle: {
              color: '#fff',
              borderColor: 'rgba(150, 150, 220, 1)',
              borderWidth: 1,
            },
            lineStyle: {
              color: 'rgba(150, 150, 220, 1)',
              width: 2,
              type: 'dashed'
            },
            ...getLimitMarkOptions()
          } as CustomChartSeries);
        }
        console.log("series", series)
        // 没有预测时间的默认单线图
        return {
          grid: {
            left: 50,
            right: 50,
            top: 30,
            bottom: 50,
          },
          dataZoom: [
            {
              type: 'inside',
              start: 0,
              end: 100,
              xAxisIndex: 0,
              filterMode: 'filter',
              zoomOnMouseWheel: true,
              moveOnMouseMove: true
            }
          ],
          legend: {
            data: series.map(item => item.name).filter(name => {
              // 如果是"实际值"，检查对应系列的数据是否为空
              if (name === '实际值') {
                const actualSeries = series.find(s => s.name === '实际值');
                return actualSeries && actualSeries.data && actualSeries.data.length > 0;
              }
              return true;
            }),
            top: 5,
            left: 'center',
            textStyle: {
              color: 'rgba(255, 255, 255, 0.8)',
              fontSize: 12,
            }
          },
          tooltip: {
            trigger: 'axis',
            formatter: createTooltipFormatter(singleTrendData.times, xAxisData),
            backgroundColor: 'rgba(50,50,50,0.9)',
            borderColor: 'rgba(255,255,255,0.3)',
            textStyle: {
              color: '#fff',
              fontSize: 12
            },
            padding: [8, 10]
          },
          xAxis: {
            type: 'time',
            axisLine: {
              show: true,
              lineStyle: { color: 'rgba(255, 255, 255, 0.3)' }
            },
            axisTick: { show: false },
            axisLabel: {
              color: 'rgba(255, 255, 255, 0.7)',
              fontSize: 10,
              rotate: 45,
              formatter: (value: string) => {
                return dayjs(value).format('HH:mm:ss');
              }
            },
          },
          yAxis: {
            type: 'value',
            show: true,
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: {
              show: true,
              lineStyle: { color: 'rgba(255, 255, 255, 0.1)' }
            },
            axisLabel: {
              show: true,
              color: 'rgba(255, 255, 255, 0.7)',
              fontSize: 10,
              formatter: (value: number) => value.toFixed(2)
            },
            min: (value: any) => {
              const calcMin = Math.floor(value.min) * 0.9;
              return lowerLimit !== undefined ? Math.min(calcMin, lowerLimit) : calcMin;
            },
            max: (value: any) => {
              const calcMax = Math.ceil(value.max) * 1.1;
              return upperLimit !== undefined ? Math.max(calcMax, upperLimit) : calcMax;
            },
          },
          series: series
        };
      }
    }

    // 如果没有数据，返回空配置
    return {};
  }, [chartData, predictTime, historyPredictData, upperLimit, lowerLimit, type]);

  const handleChartClick = useCallback((params: any) => {
    // 如果点击的不是实际值系列或没有数据索引，则直接返回
    if (params.componentType !== 'series' || params.seriesName !== '实际值' || params.dataIndex === undefined) {
      return;
    }
    let originalTimestamp: string | undefined = undefined;
    try {
      // 获取源数据，处理数组或单一数据的情况
      const sourceData = chartData && (Array.isArray(chartData) ? chartData[0] : chartData);
      if (!sourceData || !sourceData.times) {
        console.warn("点击的源数据未找到或无效。");
        return;
      }
      let relevantTimes: string[] | undefined;
      if (predictTime) {
        // 查找预测时间点在时间数组中的位置
        const splitIndex = sourceData.times.findIndex((time: string) => dayjs(time).isAfter(dayjs(predictTime)) || dayjs(time).isSame(dayjs(predictTime))) ?? -1;
        if (splitIndex === -1) { // 全部是实际值
          relevantTimes = sourceData.times;
        } else { // 分割视图
          // 检查点击是否在"实际值"系列上（假设索引为0）
          if (params.seriesIndex === 0) {
            relevantTimes = sourceData.times.slice(0, splitIndex);
          } else {
            return; // 点击了预测系列
          }
        }
      } else { // 没有预测时间分割
        relevantTimes = sourceData.times;
      }

      // 获取点击点对应的原始时间戳
      if (relevantTimes && params.dataIndex < relevantTimes.length) {
        originalTimestamp = relevantTimes[params.dataIndex];
      }

      if (originalTimestamp) {
        console.log(`点击了'实际值'点。时间: ${originalTimestamp}。正在获取新的历史数据...`);
        fetchData(originalTimestamp); // 传递点击的时间作为覆盖
      } else {
        console.warn("无法确定点击点的原始时间戳。", params, relevantTimes);
      }
    } catch (error) {
      console.error("handleChartClick中出错:", error, params);
    }
  }, [chartData, fetchData, predictTime]);


  if (!visible) return null;

  return (
    <>
      {/* 蒙层 */}
      <div className={styles['modal-overlay']} onClick={handleClose} />

      {/* 弹窗内容 */}
      <div
        className={getModalClassName()}
        ref={modalRef}
      >
        <div className={styles['modal-header']}>
          <div className={styles['modal-title']} title={title}>{title}</div>
          <button className={styles['close-btn']} onClick={handleClose}>×</button>
        </div>

        <div className={styles['modal-content']}>
          <div className={styles['point-info']}>
          </div>
          <div className={styles['chart-container']}>
            <ReactECharts
              option={getChartOptions}
              style={{ height: '100%', width: '100%' }}
              opts={{ renderer: 'canvas' }}
              showLoading={loading}
              onEvents={{
                'click': handleChartClick
              }}
            />
          </div>
        </div>
      </div>
    </>
  );
};

export default ChartPointModal;